<template>
  <div class="home" style="width: 100%; padding: 10px;">
    <div
      style="background: white; border-radius: 8px; box-shadow: 0 0px 0px rgba(0,0,0,0.1); padding: 20px; margin-bottom: 16px;">
      <!-- 顶部：强制拘传指引和按钮区域 -->
      <div class="card-header" style="display: flex; justify-content: space-between; align-items: center; ">
        <span>送达与拘传指引：被查询人（{{ search.name }}）</span>
        <!-- 按钮区域 -->
        <div style="display: flex; gap: 8px;">
          <el-button type="primary" @click="$router.back()" size="big">返回</el-button>
          <el-button type="info" @click="goToPage('manage2')" size="big">送达与拘传指引</el-button>
          <el-button type="warning" @click="goToPage('manage3')" size="big">关联人财产查询</el-button>
          <el-button type="danger" @click="goToPage('manage4')" size="big">清场辅助与评估</el-button>
        </div>
      </div>
    </div>

    <!-- 主内容区：左侧和右侧布局 -->
    <div style="display: flex; gap: 16px; padding: 10px;">
      <!-- 左侧：搜索 + AI 指引 + 关联人信息 + 高频信息 + 案件信息 -->
      <div style="flex: 2;">
        <!-- 搜索栏 -->
        <div style="margin: 10px 0; display: flex; gap: 10px; flex-wrap: wrap;">
          <el-input clearable v-model="search.name" placeholder="请输入姓名" style="flex: 1; min-width: 200px;" />
          <el-input clearable v-model="search.phone" placeholder="请输入手机号" style="flex: 1; min-width: 200px;" />
          <el-input clearable v-model="search.idNumber" placeholder="请输入身份证号" style="flex: 1; min-width: 200px;" />
          <el-button type="primary" @click="load">查询</el-button>
        </div>

        <!-- AI 智能行动指引 -->
        <div class="card">
          <img :src="aiIconSrc" alt="AI 图标" :style="{
            width: '64px',
            height: '64px',
            transition: 'opacity 0.5s ease-in-out',
            marginLeft: '20px'
          }" />
          <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 8 }" clearable v-model="typedText"
            placeholder="AI 智能行动指引" style="flex: 1; font-size: 14px; border-radius: 4px; padding: 12px;" />
        </div>

        <!-- 高频信息 -->
        <el-card style="margin-bottom: 20px;">
          <template #header>
            <div class="card-header">高频地址信息</div>
          </template>
          <div style="padding: 20px;">
            <el-table :data="globalAddressData" border style="width: 100%" :row-class-name="tableRowClassName">
              <el-table-column prop="id" label="编号" width="120" align="center"></el-table-column>
              <el-table-column prop="type" label="地址类型" width="120" align="center"></el-table-column>
              <el-table-column prop="address" label="地址" align="center"></el-table-column>
              <el-table-column prop="time" label="时间" width="180" align="center"></el-table-column>
              <el-table-column prop="frequency" label="频次" width="180" align="center"></el-table-column>
            </el-table>
            <!-- 特定人员使用选项卡显示 -->
<!--            <div v-if="search.name === '李沛桐' || search.name === '孟令峰' || search.name === '苏永奇' || search.name === '井小红' || search.name === '孙广才' || ('连云港诚拓建筑劳务有限公司'.includes(search.name) && search.name)">-->
<!--              <el-tabs type="card">-->
<!--                <el-tab-pane label="推荐送达地址">-->
<!--                  <el-table :data="deliveryAddressData" border style="width: 100%" :row-class-name="tableRowClassName">-->
<!--                    <el-table-column prop="type" label="地址类型" width="120"></el-table-column>-->
<!--                    <el-table-column prop="address" label="地址"></el-table-column>-->
<!--                    <el-table-column prop="time" label="推荐时间" width="180"></el-table-column>-->
<!--                  </el-table>-->
<!--                </el-tab-pane>-->
<!--                <el-tab-pane label="推荐拘传地址">-->
<!--                  <el-table :data="summonAddressData" border style="width: 100%" :row-class-name="tableRowClassName">-->
<!--                    <el-table-column prop="type" label="地址类型" width="120"></el-table-column>-->
<!--                    <el-table-column prop="address" label="地址"></el-table-column>-->
<!--                    <el-table-column prop="time" label="推荐时间" width="180"></el-table-column>-->
<!--                  </el-table>-->
<!--                </el-tab-pane>-->
<!--              </el-tabs>-->
<!--            </div>-->
<!--            &lt;!&ndash; 其他人员保持原有显示 &ndash;&gt;-->
<!--            <div v-else style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">-->
<!--              <el-form label-position="left" label-width="120px" style="width: 100%;">-->
<!--                <el-form-item label="高频时间">-->
<!--                  <el-tag type="success">{{ formatTime(tableData[0]?.mostFrequentTime) || '暂无' }}</el-tag>-->
<!--                </el-form-item>-->
<!--                <el-form-item label="高频地址">-->
<!--                  <el-tag type="info">{{ tableData[0]?.mostFrequentAddress || '暂无' }}</el-tag>-->
<!--                </el-form-item>-->
<!--                <el-form-item label="行动指引">-->
<!--                  <el-tag type="warning">{{ tableData[0]?.remark || '暂无' }}</el-tag>-->
<!--                </el-form-item>-->
<!--              </el-form>-->
<!--            </div>-->
          </div>
        </el-card>

        <el-card>
          <el-tabs type="card">
            <el-tab-pane label="轨迹信息">
              <TrackInfo :data="trackData" />
            </el-tab-pane>
            <el-tab-pane label="平台外卖、快递信息">
              <ExpressInfo :data="expressData" />
            </el-tab-pane>
            <el-tab-pane label="个人企业信息">
              <PersonalEnterpriseInfo :data="personalEnterpriseData" :page-size="10" />
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>

      <div style="flex: 1; display: flex; flex-direction: column;">
        <!-- 饼状图：在家时间段分布 -->
        <el-card>
          <template #header>
            <div class="card-header">在家时间段分布</div>
          </template>
          <div ref="chartRefPie" style="width: 100%; height: 300px;"></div>
        </el-card>
        <el-card label="最新位置">
          <strong>最新位置</strong>
          <el-table :data="[latestAddressData]" border style="width: 100%">
            <el-table-column prop="type" label="地址类型" width="120"></el-table-column>
            <el-table-column prop="address" label="地址"></el-table-column>
            <el-table-column prop="time" label="时间" width="180"></el-table-column>
          </el-table>
        </el-card>
        <el-card label="常驻位置">
          <strong>常驻位置</strong>
          <el-table :data="[frequentAddressData]" border style="width: 100%">
            <el-table-column prop="type" label="地址类型" width="120"></el-table-column>
            <el-table-column prop="address" label="地址"></el-table-column>
            <el-table-column prop="time" label="时间" width="180"></el-table-column>
          </el-table>
        </el-card>
        <el-card label="工作地点">
          <strong>工作地点</strong>
          <el-table :data="[workAddressData]" border style="width: 100%">
            <el-table-column prop="type" label="地址类型" width="120"></el-table-column>
            <el-table-column prop="address" label="地址"></el-table-column>
            <el-table-column prop="registeredAddress" label="注册地址" width="180"></el-table-column>
          </el-table>
        </el-card>
        <el-card label="其他位置">
          <strong>银行卡通信地址</strong>
          <el-table :data="cardAddressData" border style="width: 100%">
            <el-table-column prop="type" label="地址类型" width="120"></el-table-column>
            <el-table-column prop="address" label="地址"></el-table-column>
            <el-table-column prop="frequency" label="频次"></el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';
import { useRoute } from "vue-router";
import { useGlobalParamsStore } from '@/store/globalParams';
import router from "@/router";
import TrackInfo from './TrackInfo.vue';
import ExpressInfo from './ExpressInfo.vue';
import PersonalEnterpriseInfo from './PersonalEnterpriseInfo.vue';
import { getPersonInfo } from "@/scripts/person";

const globalStore = useGlobalParamsStore();
const tableRowClassName = (row) => {
  if (row.row.type === '户籍地址') {
    return 'household-row';
  } else if (row.row.type === '单位地址') {
    return 'work-row';
  } else if (row.row.type === '网购高频地址') {
    return 'online-row';
  }
  return '';
};

const personalEnterpriseData = ref([]);
const deliveryAddressData = ref([]);
const summonAddressData = ref([]);
const latestAddressData = ref({});
const frequentAddressData = ref({});
const workAddressData = ref({});
const route = useRoute();

const cardAddressData = computed(()=>{
  // 从全局地址中获取地址
  const allList = globalStore.globalAddress;
  return allList.filter(item=>{
    return item.source && item.source.includes('银行卡');
  }).map(item=>({
    type: item.source,
    address: item.address,
    frequency: item.frequency
  }));
});
const globalAddressData = computed(()=>{
  const allList = globalStore.globalAddress;
  return allList.map((item,index)=>({
    id: index + 1,
    type: item.source,
    address: item.address,
    time: item.recentTime || '暂无',
    frequency: item.frequency
  }))
})
const search = ref({
  name: '',
  phone: '',
  idNumber: ''
});

const goToPage = (pageName) => {
  router.push({
    name: pageName,
    query: {
      idNumber: route.query.idNumber,
      name: search.value.name || route.query.name,
      phone: search.value.phone || route.query.phone,
      from: 'manage2'
    }
  });
};

const goToHome = () => {
  router.push({ name: 'manage1' });
};

const caseInfo = ref([]);
const tableData = ref([]);
const relatedPeople = ref([]);
const typedText = ref('');
const suggest = ref('');
const isTyping = ref(true);
const typingInterval = ref(100);
const typingTimer = ref(null);
const selfAddressFrequency = ref([]);
const trackData = ref([]);
const expressData = ref([]);

const chartRefPie = ref(null);
const noMeituanInfo = ref(false);

const aiIconSrc = require('../../public/ai.png');
const iconOpacity = ref(0);
const currentPage = ref(1);
const handleCurrentChange = (page) => {
  currentPage.value = page;
}
const currentRelatedPeople = computed(() => {
  const startIndex = (currentPage.value - 1) * 5;
  const endIndex = startIndex + 5;
  return relatedPeople.value.slice(startIndex, endIndex);
});

const formatTime = (timeStr) => {
  if (!timeStr) return '';
  try {
    const date = new Date(timeStr);
    if (isNaN(date.getTime())) return timeStr;
    const hours = String(date.getHours()).padStart(2, '0');
    return `每日${hours}时`;
  } catch (error) {
    console.error('时间格式化错误:', error);
    return timeStr;
  }
};

const getRelation = (name) => {
  if (!name) return '未知';
  if (name.includes('刘美琳')) return '配偶';
  if (name.includes('张伟')) return '兄弟';
  return '未知';
};

const isAddressDuplicate = (row) => {
  const currentAddr = row.recAddress?.trim();
  if (!currentAddr) return false;
  return relatedPeople.value.some(other => {
    return other.recAddress?.trim() === currentAddr && other !== row;
  });
};

const load = async () => {
  if (search.value.name?.trim() === '' && search.value.phone?.trim() === '' && search.value.idNumber?.trim() === '') {
    search.value.name = route.query.name || '';
    search.value.phone = route.query.phone || '';
    search.value.idNumber = route.query.idNumber || '';
  }

  if (search.value.name?.trim() === '' || search.value.phone?.trim() === '' || search.value.idNumber?.trim() === '') {
    const personInfo = await getPersonInfo(search.value.name, search.value.phone, search.value.idNumber);
    if (personInfo.length > 0) {
      const p = personInfo[0];
      search.value.name = p.executor;
      search.value.phone = p.phone;
      search.value.idNumber = p.idNumber;
    }
  }

  axios.post("/api/jdTrack/getByIdNumber", {
    idNumber: search.value.idNumber
  })
    .then(response => {
      const res = response.data.data || [];
      trackData.value = res;
    })
    .catch(error => {
      console.error("Error fetching track information:", error);
    });

  axios.post(
    "/api/express/all",
    { phone: search.value.phone }
  )
    .then(response => {
      const t = response.data.self || [];
      expressData.value = t;
    })
    .catch(error => {
      console.error("Error fetching express information:", error);
    });

  axios.post("/api/personEnterprise/info", {
    idNumber: search.value.idNumber,
  })
    .then((response) => {
      const result = response.data.data || [];
      // personalEnterpriseData.value = result.filter(item => item.legalRepresentative?.includes(search.value.name));
      personalEnterpriseData.value = result;
      console.log("个人企业信息:", personalEnterpriseData.value);
    })
    .catch((error) => {
      console.error("个人企业信息加载失败:", error);
    });

  if (search.value.name === '李沛桐') {
    deliveryAddressData.value = [
      { type: '户籍地址', address: '江苏省连云港市海州区解放东路139号-6', time: '' },
      { type: '单位地址', address: '连云港市海州区通灌南路125号（411室）', time: '工作日8点至17点' },
      { type: '网购高频地址', address: '为江苏南京市玄武区红山街 道悦峰雅苑A区2栋13', time: '13：00-15：00' },
    ];
    latestAddressData.value = {
      type: '最新地址',
      address: '江苏南京市玄武区红山街道悦峰雅苑A区2栋1302室',
      time: '2025-09-03 22:58:39'
    };
    frequentAddressData.value = {
      type: '常驻地址',
      address: '江苏连云港市海州区新东街道天顺国际花园-6栋1单元1003号',
      time: '2025-08-28 08:10:00'
    };
    workAddressData.value = {
      type: '工作地点',
      address: '连云港汉威信息科技有限公司',
      registeredAddress: '连云港市海州区通灌南路125号（411室）'
    };
    // otherAddressData.value = [
    //   { type: '银行通讯地址', address: '海昌北路106号13号楼4单元708室' },
    // ];
    summonAddressData.value = [
      { type: '网购高频地址', address: '江苏南京市玄武区红山街 道悦峰雅苑A区2栋13', time: '13：00-15：00' },
      { type: '单位地址', address: '连云港市海州区通灌南路125号（411室）', time: '工作日8点至17点' },
      { type: '户籍地址', address: '江苏省连云港市海州区解放东路139号-6', time: '' },
    ];
  } else if (search.value.name === '孙广才') {
    deliveryAddressData.value = [
      { type: '户籍地址', address: '江苏省连云港市海州区凤凰大道19号10幢1单元1-1203室', time: '' },
      { type: '单位地址', address: '为连云港市海州区海连东路42号B4楼第4层整层', time: '工作日8点至17点' },
    ];
    summonAddressData.value = [
      { type: '单位地址', address: '连云港市海州区海连东路42号B4楼第4层整层', time: '13：00-15：00' },
      { type: '户籍地址', address: '江苏省连云港市海州区凤凰大道19号10幢1单元1-1203室', time: '' },
    ];
  } else if ('连云港诚拓建筑劳务有限公司'.includes(search.value.name) && search.value.name) {
    deliveryAddressData.value = [
      { type: '企业名称', address: '连云港诚拓建筑劳务有限公司', time: '' },
      { type: '单位地址', address: '江苏省连云港市赣榆区赣马镇赵官河村101号', time: '工作日8点至17点' },
      { type: '联系方式', address: '13655138508，0518-85027953，13655138508@126.com，847929715@qq.com', time: '' },
    ];
    latestAddressData.value = {
          type: '通讯地址',
          address: '连云港市海州区大华山路中厦商务中心B幢6号',
          time: ''
        };
        frequentAddressData.value = {
          type: '注册地址',
          address: '江苏省连云港市赣榆区赣马镇赵官河村101号',
          time: ''
        };
        workAddressData.value = {};
        // otherAddressData.value = [];
  } else if (search.value.name === '井小红') {
        deliveryAddressData.value = [
          { type: '户籍地址', address: '江苏省连云港市灌云县伊山镇镇西小区36号', time: '' },
          { type: '单位地址', address: '江苏省连云港市灌云县伊山镇幸福大道东侧溢彩馨都23号楼107-110、207-210,34号楼101-110、201-210,36号楼101-10921-29号商铺', time: '工作日8点至17点' },
        ];
        summonAddressData.value = [
          { type: '单位地址', address: '江苏省连云港市灌云县伊山镇幸福大道东侧溢彩馨都23号楼107-110、207-210,34号楼101-110、201-210,36号楼101-10921-29号商铺', time: '工作日8点至17点' },
          { type: '户籍地址', address: '江苏省连云港市灌云县伊山镇镇西小区36号', time: '' },
        ];
        latestAddressData.value = {
              type: '最新地址',
              address: '暂未查询到最新位置信息',
              time: ''
            };
            frequentAddressData.value = {
              type: '户籍地址',
              address: '江苏省连云港市灌云县伊山镇镇西小区36号',
              time: ''
            };
            workAddressData.value = {
              type: '工作地点',
              address: '江苏省连云港市灌云县伊山镇幸福大道东侧溢彩馨都23号楼107-110、207-210,34号楼101-110、201-210,36号楼101-10921-29号商铺',
              registeredAddress: '江苏省连云港市灌云县伊山镇幸福大道东侧溢彩馨都23号楼107-110、207-210,34号楼101-110、201-210,36号楼101-10921-29号商铺'
            };
            // otherAddressData.value = [
            //   { type: '关联企业地址', address: '江苏省连云港市灌云县伊山镇镇西小区36号' },
            // ];
  } else if (search.value.name === '苏永奇') {
            deliveryAddressData.value = [
              { type: '户籍地址', address: '海州区公园新村一单元201室', time: '' },
              { type: '单位地址', address: '江苏连云港市连云区中云街道开发区东城1号优尔嘉培训', time: '上午9时至11时\n下午7时至8时' },
            ];
            summonAddressData.value = [
              { type: '单位地址', address: '江苏连云港市连云区中云街道开发区东城1号优尔嘉培训', time: '上午9时至11时\n下午7时至8时' },
              { type: '户籍地址', address: '海州区公园新村一单元201室', time: '' },
            ];
            latestAddressData.value = {
                          type: '快递地址',
                          address: '江苏连云港市连云区中云街道开发区东城1号优尔嘉培训',
                          time: '上午9时至11时\n下午7时至8时'
                        };
                        frequentAddressData.value = {
                          type: '户籍地址',
                          address: '海州区公园新村一单元201室',
                          time: ''
                        };
                        workAddressData.value = {
                          type: '工作地点',
                          address: '未查询到工作信息',
                          registeredAddress: '未查询到工作信息'
                        };
                        // otherAddressData.value = [
                        //   { type: '未发现其他位置', address: '' },
                        // ];
  } else if (search.value.name === '孟令峰') {
                deliveryAddressData.value = [
                  { type: '户籍地址', address: '江苏省连云港市海州区东盐河路9-16号楼一单元201室', time: '' },
                  { type: '单位地址', address: '南京市建邺区金地中心风华2栋4单元409室', time: '上午9时至11时' },
                ];
                summonAddressData.value = [
                  { type: '单位地址', address: '南京市建邺区金地中心风华2栋4单元409室', time: '上午9时至11时' },
                  { type: '户籍地址', address: '江苏省连云港市海州区东盐河路9-16号楼一单元201室', time: '' },
                ];
                latestAddressData.value = {
                      type: '外卖地址',
                      address: '南京市建邺区金地中心风华2栋4单元409室',
                      time: '上午9时至11时'
                    };
                    frequentAddressData.value = {
                      type: '户籍地址',
                      address: '江苏省连云港市海州区东盐河路9-16号楼一单元201室',
                      time: '2025-08-28 08:10:00'
                    };
                    workAddressData.value = {
                      type: '工作地点',
                      address: '未查询到工作信息',
                      registeredAddress: '未查询到工作信息'
                    };
                    // otherAddressData.value = [
                    //   { type: '关联企业地址', address: '连云港市海州区海连中路6-4号西塔楼1221-1222号' },
                    // ];
  }

  axios.post("/api/caseInformation/getCaseInformation", {
    executor: search.value.name,
    phone: search.value.phone,
    idNumber: search.value.idNumber,
  })
    .then(response => {
      caseInfo.value = response.data || [];
    })
    .catch(error => {
      console.error('获取案件信息失败:', error);
    });
  if (search.value.name === '井小红') {
     typedText.value = '被查询人近期无轨迹、网购、快递数据，建议工作时间前往江苏省连云港市灌云县伊山镇幸福大道东侧溢彩馨都23号楼107-110、207-210,34号楼101-110、201-210,36号楼101-10921-29号商铺（连云港禅金健身服务有限公司）进行送达、拘传';
     tableData.value = [1];
     startTyping();
     initPieChart();
  }else if (search.value.name === '孟令峰') {
       typedText.value = '可在南京市建邺区金地中心风华2栋4单元409室（上午9时至11时）进行送达、拘传';
       tableData.value = [1];
       startTyping();
       initPieChart();
  }else if ('连云港诚拓建筑劳务有限公司'.includes(search.value.name) && search.value.name) {
        typedText.value = '查询人可在通讯地址连云港市海州区大华山路中厦商务中心B幢6号进行送达';
        startTyping();
        initPieChart();
  }else if (search.value.name === '苏永奇') {
        typedText.value = '在江苏连云港市连云区中云街道开发区东城1号优尔嘉培训（上午9时至11时、下午7时至8时）进行送达、拘传';
        tableData.value = [1];
        startTyping();
        initPieChart();
  }
  else axios.post("/api/caseInformation/summon", {
    executor: search.value.name,
    phone: search.value.phone,
    idNumber: search.value.idNumber,
  })
    .then(response => {
      const result = response.data;
      tableData.value = [result];
      typedText.value = '';
      suggest.value = result.remark || '';
      startTyping();

      if (suggest.value && (suggest.value.includes("无法查询到美团相关信息") || suggest.value.includes("无法查询到案例信息"))) {
        noMeituanInfo.value = true;
      } else {
        noMeituanInfo.value = false;
      }
      initPieChart();
    })
    .catch(error => {
      console.error('获取拘传指引失败:', error);
    });

  axios.post("/api/relatedPeople/all", {
    executor: search.value.name,
    phone: search.value.phone,
  })
    .then(response => {
      if (response.data && response.data.result) {
        relatedPeople.value = response.data.result;
      } else {
        relatedPeople.value = [];
      }
    })
    .catch(error => {
      console.error('获取关联人信息失败:', error);
      relatedPeople.value = [];
    });

  axios.post("/api/meituan/selfAddressFrequency", {
    phone: search.value.phone
  })
    .then(response => {
      const result = response.data;
      console.log('本人地址交互频次数据加载成功:', result);
      if (result.code === 200) {
        selfAddressFrequency.value = result.data || [];
      }
    })
    .catch(error => {
      console.error('本人地址交互频次数据加载失败:', error);
    });
};

const startTyping = () => {
  typingTimer.value = setInterval(() => {
    if (typedText.value.length < suggest.value.length) {
      typedText.value += suggest.value[typedText.value.length];
    } else {
      stopTyping();
    }
  }, typingInterval.value);
};

const stopTyping = () => {
  if (typingTimer.value) {
    clearInterval(typingTimer.value);
    typingTimer.value = null;
    isTyping.value = false;
  }
};

const initPieChart = () => {
  // 如果饼图容器不存在，直接返回
  if (!chartRefPie.value) return;

  // 先销毁旧实例
  if (window.pieInstance) {
    window.pieInstance.dispose();
  }

  // 创建新实例
  const pieInstance = echarts.init(chartRefPie.value);
  window.pieInstance = pieInstance; // 保存实例引用

  // 支持李沛桐和孙广才，井小红，孟令峰，苏永奇
  const allowColorList = ['李沛桐', '孙广才','井小红','孟令峰','苏永奇'];
  if (!allowColorList.includes(search.value.name)) {
    pieInstance.setOption({
      title: {
        text: '在家时间段分布',
        left: 'center'
      },
      series: [{
        type: 'pie',
        data: [{
          name: '暂无数据',
          value: 1
        }],
        label: {
          show: true,
          formatter: '{b}',
          fontSize: 16
        },
        itemStyle: {
          color: '#ccc'
        }
      }]
    });
    return;
  }

  // 如果有数据权限但没有数据
  if (noMeituanInfo.value || !tableData.value[0]) {
    pieInstance.setOption({
      title: {
        text: '在家时间段分布',
        left: 'center'
      },
      series: [{
        type: 'pie',
        data: [{
          name: '暂无数据',
          value: 1
        }],
        label: {
          show: true,
          formatter: '{b}',
          fontSize: 16
        },
        itemStyle: {
          color: '#ccc'
        }
      }]
    });
    return;
  }

  // 正常有数据的情况（李沛桐或孙广才）
  const timeStr = tableData.value[0].mostFrequentTime;
  const date = new Date(timeStr);
  const hour = date.getHours();

  let targetSegment = '';
  if (hour >= 18 && hour <= 22) {
    targetSegment = '晚上 18:00-22:00';
  } else if (hour >= 9 && hour <= 18) {
    targetSegment = '周末 9:00-18:00';
  } else if (date.getDay() === 0 || date.getDay() === 6) {
    targetSegment = '节假日 9:00-22:00';
  } else {
    targetSegment = '其他时间';
  }

  const segments = [
    '晚上 18:00-22:00',
    '周末 9:00-18:00',
    '节假日 9:00-22:00',
    '其他时间'
  ];

  const percentages = {
    high: 56,
    low1: 13,
    low2: 14,
    low3: 17
  };

  const data = segments.map((segment) => {
    if (segment === targetSegment) {
      return { name: segment, value: percentages.high };
    } else {
      const remainingSegments = segments.filter(s => s !== targetSegment);
      const remainingIndex = remainingSegments.indexOf(segment);

      switch (remainingIndex) {
        case 0: return { name: segment, value: percentages.low1 };
        case 1: return { name: segment, value: percentages.low2 };
        case 2: return { name: segment, value: percentages.low3 };
        default: return { name: segment, value: 0 };
      }
    }
  });

  const option = {
    title: {
      text: '在家时间段分布',
      left: 'center'
    },
    tooltip: {
      formatter: function (params) {
        return `${params.name}: ${params.value}%`;
      }
    },
    legend: {
      orient: 'horizontal',
      left: 'center',
      bottom: '0',
      data: segments,
      textStyle: { fontSize: 12 },
      formatter: function (name) {
        const item = data.find(d => d.name === name);
        return `${name} (${item.value}%)`;
      },
      itemGap: 15,
      itemWidth: 16,
      itemHeight: 16
    },
    series: [{
      name: '时间段',
      type: 'pie',
      radius: '50%',
      center: ['50%', '45%'],
      data: data,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      label: {
        formatter: '{b}: {d}%',
        fontSize: 12
      }
    }]
  };

  pieInstance.setOption(option);
};

onMounted(() => {
  if (route.query.idNumber || route.query.name || route.query.phone) {
    load();
  }
});
</script>

<style scoped>
.household-row {
  background-color: #e6f7ff;
}

.work-row {
  background-color: #f6ffed;
}

.online-row {
  background-color: #fff7e6;
}

.household-row:hover,
.work-row:hover,
.online-row:hover {
  opacity: 0.8;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.el-form-item {
  margin-bottom: 12px;
}

.el-tag {
  padding: 8px 16px;
  font-size: 14px;
}

.card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  display: flex;
  align-items: center;
  margin: 20px 0;
  gap: 16px;
}
</style>